package bamin.com.bamindaijia.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.utils.ACache;
import com.alibaba.fastjson.JSON;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.Tip;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import bamin.com.bamindaijia.R;
import bamin.com.bamindaijia.adapter.MyChooseAdapter;
import bamin.com.bamindaijia.adapter.MySearchAdapter;
import bamin.com.bamindaijia.constant.Constant;
import bamin.com.bamindaijia.model.CityCode;
import bamin.com.bamindaijia.model.HistoryEndSite;
import bamin.com.bamindaijia.model.HistoryEndSiteList;
import bamin.com.bamindaijia.model.MyLatLonPoint;
import bamin.com.bamindaijia.model.MyTip;
import cn.qqtheme.framework.util.ConvertUtils;


public class ChosseSite extends ZjbBaseActivity implements View.OnClickListener {

    private ListView mListView_site;
    private MyChooseAdapter mAdapter;
    private View mSite_head;
    private LatLng mStart_site;
    private List<PoiItem> mPois = new ArrayList<>();
    private EditText mEditText_where;
    private Inputtips mInputtips;
    private TextView mTextView_city;
    private String mCity;
    private String mCityCode;
    private ListView mListView_search;
    private List<Tip> listSearch = new ArrayList<>();
    private MySearchAdapter mAdapterSearch;
    private String mChosseType;
    private boolean isAddCommonly;
    private TextView mTv_home;
    private TextView mTv_company;
    private MyTip tip_home;
    private MyTip tip_company;
    private GeocodeSearch mGeocodeSearch;
    private boolean hasCode;
    private List<HistoryEndSite> mHistoryEndSiteList = new ArrayList<>();
    private ACache mACache;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chosse_site);
        init();
    }

    @Override
    protected void initData() {

    }


    @Override
    protected void onStart() {
        super.onStart();
        ACache aCache = ACache.get(ChosseSite.this);
        tip_home = (MyTip) aCache.getAsObject(Constant.ACACHE.TIP_HOME);
        tip_company = (MyTip) aCache.getAsObject(Constant.ACACHE.TIP_COMPANY);
        if (tip_home != null) {
            String homeName = tip_home.getName();

            Log.e("tip_home", tip_home.toString());
            if (!homeName.equals("")) {
                Log.e("homeName", homeName);
                mTv_home.setText(homeName);
            }
        }

        if (tip_company != null) {
            Log.e("tip_company", tip_company.toString());
            String companyName = tip_company.getName();
            if (!companyName.equals("")) {
                Log.e("companyName", companyName);
                mTv_company.setText(companyName);
            }
        }


    }

    @Override
    protected void initViews() {
        mListView_site.addHeaderView(mSite_head);
        mTextView_city.setText(mCity);
        mAdapterSearch = new MySearchAdapter(this, listSearch);
        mListView_search.setAdapter(mAdapterSearch);
        if (Constant.INTENT_KEY.START.equals(mChosseType)) {
            mAdapter = new MyChooseAdapter(this, mPois);
            mListView_site.setAdapter(mAdapter);
            mEditText_where.setHint("你从哪里出发");
            fanBianMa();
            LatLonPoint latLonPoint = new LatLonPoint(mStart_site.latitude, mStart_site.longitude);
            Log.e("initViews ", "initViews 传过来的坐标" + latLonPoint.toString());
            getAddress(latLonPoint);
        } else if (Constant.INTENT_KEY.END.equals(mChosseType)) {
            mEditText_where.setHint("你要到哪里去");
            mAdapter = new MyChooseAdapter(this, mHistoryEndSiteList, 1);
            mListView_site.setAdapter(mAdapter);
            Log.e("initViews ", "initViews mHistoryEndSiteList" + mHistoryEndSiteList.size());
        }
    }

    @Override
    protected void setListeners() {
        mEditText_where.addTextChangedListener(new MyTextWatcher());
        mInputtips = new Inputtips(ChosseSite.this, new Inputtips.InputtipsListener() {
            @Override
            public void onGetInputtips(List<Tip> list, int i) {
                listSearch.addAll(list);

//                for (int j = 0; j < listSearch.size(); j++) {
//                    Tip tip = listSearch.get(j);
//                    if (TextUtils.isEmpty(tip.getAdcode()) || TextUtils.isEmpty(tip.getAddress()) || TextUtils.isEmpty(tip.getDistrict()) ) {
//                        Log.e("ChosseSite", "onGetInputtips: --->>" + tip.getName());
//
//                        listSearch.remove(j);
//                    }
//                }
                Iterator<Tip> iterator = listSearch.iterator();
                while(iterator.hasNext()){
                    Tip tip = iterator.next();
                    if (TextUtils.isEmpty(tip.getAdcode()) || TextUtils.isEmpty(tip.getAddress()) || TextUtils.isEmpty(tip.getDistrict()) ) {
                        Log.e("ChosseSite", "onGetInputtips: --->>" + tip.getName());

                        iterator.remove();
                    }

                }
                mAdapterSearch.notifyDataSetChanged();
                for (int j = 0; j < list.size(); j++) {
                    Log.e("onGetInputtips", "提示返回结果" + list.get(j).getName());
                    Log.e("onGetInputtips ", "onGetInputtips getDistrict" + list.get(j).getDistrict());
                    Log.e("onGetInputtips ", "onGetInputtips getAdcode" + list.get(j).getAdcode());
                    Log.e("onGetInputtips ", "onGetInputtips getAddress" + list.get(j).getAddress());
                }
            }
        });
        findViewById(R.id.textView_cancle).setOnClickListener(this);
        findViewById(R.id.relaL_address_company).setOnClickListener(this);
        findViewById(R.id.relaL_address_home).setOnClickListener(this);
        mTextView_city.setOnClickListener(this);
        mListView_site.setOnItemClickListener(new MySiteOnItemClickListener());
        mListView_search.setOnItemClickListener(new MySearchOnItemClickListener());
        findViewById(R.id.textView_clear).setOnClickListener(this);
    }

    @Override
    protected void initSP() {
        mACache = ACache.get(ChosseSite.this, Constant.ACACHE.HISTORY_SITE_LIST);
        HistoryEndSiteList mAsObject = (HistoryEndSiteList) mACache.getAsObject(Constant.ACACHE.HISTORY_SITE_LIST);
        if (mAsObject != null) {
            List<HistoryEndSite> historyEndSiteList = mAsObject.getHistoryEndSiteList();
            Collections.reverse(historyEndSiteList);
            mHistoryEndSiteList.addAll(historyEndSiteList);
        }
    }

    protected void initIntent() {
        Intent intent = getIntent();
        mStart_site = intent.getParcelableExtra(Constant.INTENT_KEY.START_SITE);
        Log.e("initIntent ", "chosseSite坐标" + mStart_site.toString());
        mCity = intent.getStringExtra(Constant.INTENT_KEY.CITY);
        mCityCode = intent.getStringExtra(Constant.INTENT_KEY.CITY_CODE);
        mChosseType = intent.getStringExtra(Constant.INTENT_KEY.CHOSSE_TYPE);
        Log.e("initIntent", "选择方式" + mChosseType);

        isAddCommonly = intent.getBooleanExtra(Constant.INTENT_KEY.COMMONLY_ADDRESS, false);
        Log.e("isAddCommonly", "添加常用地址" + isAddCommonly);
    }

    protected void findID() {
        mListView_site = (ListView) findViewById(R.id.listView_site);
        mSite_head = getLayoutInflater().inflate(R.layout.site_head, null);
        mEditText_where = (EditText) findViewById(R.id.editText_where);
        mTextView_city = (TextView) findViewById(R.id.textView_city);
        mListView_search = (ListView) findViewById(R.id.listView_search);
        mTv_home = (TextView) mSite_head.findViewById(R.id.tv_address_home);
        mTv_company = (TextView) mSite_head.findViewById(R.id.tv_address_company);
    }

    class MySiteOnItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            position = position - 1;
            if (TextUtils.equals(Constant.INTENT_KEY.END, mChosseType)) {
                HistoryEndSite historyEndSite = mHistoryEndSiteList.get(position);
                resultAddress(historyEndSite.getName(), new LatLonPoint(historyEndSite.getLat(), historyEndSite.getLng()), historyEndSite.getAddress());
            } else {
                PoiItem poiItem = mPois.get(position);
                String title = poiItem.getTitle();
                LatLonPoint latLonPoint = poiItem.getLatLonPoint();
                String adName = poiItem.getAdName();
                resultAddress(title, latLonPoint, adName);
            }
        }
    }

    class MySearchOnItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            LatLonPoint point = listSearch.get(position).getPoint();
            String name = listSearch.get(position).getName();
            String address = listSearch.get(position).getDistrict();
            Log.e("onItemClick ", "onItemClick 地址" + address);
            resultAddress(name, point, address);

            HistoryEndSite historyEndSite = new HistoryEndSite(name, mCity, address, point.getLatitude(), point.getLongitude());
            if (mHistoryEndSiteList.size() >= 20) {
                mHistoryEndSiteList.remove(0);
            }
            if (mHistoryEndSiteList.size() > 0) {
                for (int i = 0; i < mHistoryEndSiteList.size(); i++) {
                    if (TextUtils.equals(mHistoryEndSiteList.get(i).getName(), name) && TextUtils.equals(mHistoryEndSiteList.get(i).getAddress(), address)) {

                    } else {
                        mHistoryEndSiteList.add(historyEndSite);
                        mACache.put(Constant.ACACHE.HISTORY_SITE_LIST, new HistoryEndSiteList(mHistoryEndSiteList));
                        break;
                    }
                }
            } else {
                mHistoryEndSiteList.add(historyEndSite);
                mACache.put(Constant.ACACHE.HISTORY_SITE_LIST, new HistoryEndSiteList(mHistoryEndSiteList));
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == Constant.REQUEST_RESULT_CODE.CHOOSE_CITY && resultCode == Constant.REQUEST_RESULT_CODE.CHOOSE_CITY) {
                mCity = data.getStringExtra(Constant.INTENT_KEY.CITY);
                Log.e("CHOOSE_CITY", mCity);
                mTextView_city.setText(mCity);
                mEditText_where.setText("");
                try {
                    String json = ConvertUtils.toString(getAssets().open("cityCode.json"));
                    List<CityCode> cityCodes = JSON.parseArray(json, CityCode.class);
                    for (int i = 0; i < cityCodes.size(); i++) {
                        CityCode cityCode = cityCodes.get(i);
                        String city = cityCode.getCity();
                        if (TextUtils.equals(city, mCity)) {
                            mCityCode = cityCode.getCode();

                        }
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }


//                getLatlon("政府", mCity);
                Log.e("ChosseSite", "城市code: --->>" + mCityCode);


                mAdapter.notifyDataSetChanged();
            }

        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.textView_clear:
                mHistoryEndSiteList.clear();
                mAdapter.notifyDataSetChanged();
                mACache.clear();
                Toast.makeText(ChosseSite.this, "清除完成", Toast.LENGTH_SHORT).show();
                break;
            case R.id.textView_cancle:
                finishTo();
                break;
            case R.id.textView_city:
                intent.setClass(this, CityPickerActivity.class);
                startActivityForResultTo(intent, Constant.REQUEST_RESULT_CODE.CHOOSE_CITY);
                break;
            case R.id.relaL_address_company:
                //判断，如果常用地址有数据，则跳转回主界面，如果没有，则跳转到设置界面
                if (mTv_company.getText().toString().equals("设置公司地址")) {
                    intent.setClass(this, AddComAddressActivity.class);
                    intent.putExtra(Constant.INTENT_KEY.CHOSSE_TYPE, Constant.INTENT_KEY.COMMONLY_ADDRESS_COMPANY);
                    intent.putExtra(Constant.INTENT_KEY.CITY_CODE, mCityCode);
                    intent.putExtra(Constant.INTENT_KEY.CITY, mCity);
                    startActivityTo(intent);
                } else {
                    MyLatLonPoint point = tip_company.getPoint();
                    LatLonPoint latLonPoint = new LatLonPoint(point.getLatitude(), point.getLongitude());
                    resultAddress(tip_company.getName(), latLonPoint, "");
                }
                break;
            case R.id.relaL_address_home:
                //判断，如果常用地址有数据，则跳转回主界面，如果没有，则跳转到设置界面
                if (mTv_home.getText().toString().equals("设置家的地址")) {
                    intent.setClass(this, AddComAddressActivity.class);
                    intent.putExtra(Constant.INTENT_KEY.CHOSSE_TYPE, Constant.INTENT_KEY.COMMONLY_ADDRESS_HOME);
                    intent.putExtra(Constant.INTENT_KEY.CITY_CODE, mCityCode);
                    intent.putExtra(Constant.INTENT_KEY.CITY, mCity);
                    startActivityTo(intent);
                } else {
                    MyLatLonPoint point = tip_home.getPoint();
                    LatLonPoint latLonPoint = new LatLonPoint(point.getLatitude(), point.getLongitude());
                    resultAddress(tip_home.getName(), latLonPoint, "");
                }
                break;
        }
    }

    /**
     * 返回起点或终点的数据
     *
     * @param name        地址名
     * @param latLonPoint 地址坐标
     */
    private void resultAddress(String name, LatLonPoint latLonPoint, String address) {
        Intent intent = new Intent();
        if (Constant.INTENT_KEY.START.equals(mChosseType)) {
            intent.putExtra(Constant.INTENT_KEY.START_SITE_BACK, name);
            intent.putExtra(Constant.INTENT_KEY.START_LATLNG_BACK, latLonPoint);
            intent.putExtra(Constant.INTENT_KEY.CITY, mCity);
            intent.putExtra(Constant.INTENT_KEY.CHOSSE_SITE_ADDRESS_START, address);
            setResult(Constant.REQUEST_RESULT_CODE.CHOSSE_START_SITE, intent);
        } else if (Constant.INTENT_KEY.END.equals(mChosseType)) {
            intent.putExtra(Constant.INTENT_KEY.END_SITE_BACK, name);
            intent.putExtra(Constant.INTENT_KEY.END_LATLNG_BACK, latLonPoint);
            intent.putExtra(Constant.INTENT_KEY.CITY, mCity);
            intent.putExtra(Constant.INTENT_KEY.CHOSSE_SITE_ADDRESS_END, address);
            setResult(Constant.REQUEST_RESULT_CODE.CHOSSE_END_SITE, intent);
        }
        finishTo();
    }

    //地理坐标转换为中文地址
    private void fanBianMa() {
        mGeocodeSearch = new GeocodeSearch(ChosseSite.this);
        mGeocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();

                Log.e("onRegeocodeSearched",
                        regeocodeAddress.getBusinessAreas().get(0).getName()
                                + "\n" + regeocodeAddress.getAois().get(0).getAoiName()
                                + "\n" + regeocodeAddress.getCrossroads().get(0).getFirstRoadName()
                                + "\n" + regeocodeAddress.getRoads().size()
                );
                mCityCode = regeocodeAddress.getCityCode();
                mPois.clear();
                mPois.addAll(regeocodeAddress.getPois());
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onGeocodeSearched(GeocodeResult result, int rCode) {
//                if (rCode == 1000) {
//                    if (result != null && result.getGeocodeAddressList() != null
//                            && result.getGeocodeAddressList().size() > 0) {
//
//                        GeocodeAddress address = result.getGeocodeAddressList().get(0);
//                        String adcode = address.getAdcode();
//                        Log.e("CityPickerActivity", "adcode: --->>" + adcode);
//
//                        LatLonPoint mLatLonPoint = address.getLatLonPoint();
//                        String mFormatAddress = address.getFormatAddress();
//                        String addressName = "经纬度值:" + mLatLonPoint + "\n位置描述:"
//                                + mFormatAddress;
//                        Log.e("CityPickerActivity", "Geo" + addressName);
//
////                        Toast.makeText(ChosseSite.this, addressName, Toast.LENGTH_SHORT).show();
//                        hasCode = true;
//                        getAddress(mLatLonPoint);
//                    } else {
////                        getLatlon();
//                        hasCode = false;
//                        Toast.makeText(ChosseSite.this, "对不起，没有搜索到相关数据！", Toast.LENGTH_SHORT).show();
//                    }
//                } else {
//                    hasCode = false;
//
//                    Toast.makeText(ChosseSite.this, "对不起，没有搜索到相关数据！", Toast.LENGTH_SHORT).show();
//                }
//                if (!hasCode) {
////                    getLatlon("医院", mCity);
//                }
            }
        });
    }

    /**
     * 响应地理编码
     */
    public void getLatlon(final String name, String city) {
        GeocodeQuery query = new GeocodeQuery(name, city);// 第一个参数表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode，
        mGeocodeSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求
    }

    /**
     * 响应逆地理编码
     */
    public void getAddress(final LatLonPoint latLonPoint) {
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500,
                GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        mGeocodeSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
    }

    class MyTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Log.e("onTextChanged", "" + s);
            try {
                listSearch.clear();
                mAdapter.notifyDataSetChanged();
                mAdapterSearch.notifyDataSetChanged();
                if (!"".equals(s)) {

                    mInputtips.requestInputtips(s + "", "" + mCityCode);
                    // TODO: 2016/9/1  
                    mListView_site.setVisibility(View.GONE);
                    mListView_search.setVisibility(View.VISIBLE);
                }
            } catch (AMapException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            Log.e("afterTextChanged", "" + s);
            if (s.length() == 0) {
                mListView_site.setVisibility(View.VISIBLE);
                mListView_search.setVisibility(View.GONE);
            }
        }
    }
}
